﻿using AutoMapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Implement;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.Useres;
using MediatR;
using Microsoft.Extensions.Logging;
using MySqlX.XDevAPI.Common;
using SCM.Domain;
using Serilog.Core;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.Useres
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, ApiResult<int>>
    {
        IBaseRepository<Users> Users;
        IMapper mapper;
        DatabaseContext db;
        public AddUserCommandHandler(IBaseRepository<Users> Users, IMapper mapper, DatabaseContext db)
        {
            this.Users = Users;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> apiResult=new ApiResult<int>();
            try
            {
                var Chename = db.SqlSugar.Queryable<Users>().Where(c => c.User_Name == request.User_Name
                && !c.IsDel).Count();
                if (Chename > 0)
                {
                    apiResult.Code = ApiEnum.error;
                    apiResult.Message = "该用户已存在";
                    apiResult.Data = 0;
                    return apiResult;
                }
                var Nid = 1;
                var fistlist=db.SqlSugar.Queryable<Users>().OrderByDescending(c => c.User_WorkCode).First();
                if (fistlist!= null)
                {
                    Nid = Convert.ToInt32(fistlist.User_WorkCode.Replace("sc",""));
                    Nid++;
                }


                var model = mapper.Map<Users>(request);
                model.CreateTime = DateTime.Now;
                model.User_WorkCode = "sc" + Nid.ToString().PadLeft(5, '0');
                int Ccout = Users.InsertAsync(model).Result;
                if (Ccout > 0)
                {
                    apiResult.Code = ApiEnum.success;
                    apiResult.Message = "添加成功";
                    apiResult.Data = 1;
                }
                else 
                {
                    apiResult.Code = ApiEnum.error;
                    apiResult.Message = "添加失败";
                    apiResult.Data = 0;
                }
                //来个异常数字测试
                //int a = 0;
                //int b = 1 / a;



            }
            catch (Exception ex)
            {     apiResult.Code = ApiEnum.error;
                apiResult.Message =ex.Message;
                //logger.LogError(ex, "添加信息异常");
                throw;
           

            }
        return apiResult;
        }
    }
}
